package com.benyq.networkprogramme

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import kotlinx.android.synthetic.main.activity_web_view.*
import java.io.File

class WebViewActivity : AppCompatActivity() {

    private lateinit var mWebView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)
        initView()

        ivBack.setOnClickListener {
            finish()
        }
        ivGo.setOnClickListener{
            mWebView?.loadUrl("http://${etUrl.text}")
        }
    }

    override fun onDestroy() {
        mWebView?.run{

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            val parent: ViewGroup = parent as ViewGroup
            parent.removeView(mWebView)

            stopLoading()
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            settings.javaScriptEnabled = false
            clearHistory()
            removeAllViews()
            destroy()

        }

        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()){
            mWebView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun initView() {
        progressBar.visibility = View.VISIBLE
        mWebView = WebView(this)
        mWebView.webViewClient = object: WebViewClient(){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                Log.e("onReceivedError",url)
                if (url.startsWith("http") || url.startsWith("https")){
                    mWebView.loadUrl(url)
                }else {
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                    }catch (e: Exception){
                        Log.e("onReceivedError", e.message)
                        return true
                    }
                }
                return true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                etUrl.setText(url)
                progressBar.visibility = View.GONE
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
            }
        }
        mWebView.webChromeClient = object: WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                progressBar.progress = newProgress
            }

        }

        val webSetting = mWebView.settings
        webSetting.javaScriptEnabled = true
        webSetting.useWideViewPort = true// 设置此属性，可任意比例缩放
        webSetting.loadWithOverviewMode = true//适配
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        webSetting.javaScriptCanOpenWindowsAutomatically = true
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        webSetting.builtInZoomControls = true
        webSetting.setSupportZoom(true)
        webSetting.loadWithOverviewMode = true
        webSetting.setGeolocationEnabled(true)
        webSetting.domStorageEnabled = true//false导致js不能转跳
        webSetting.pluginState = WebSettings.PluginState.ON;
        mWebView.requestFocus()
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        mWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        }
        fl_content.addView(mWebView)
        //  web_view.loadUrl("http://beidou.edianlai.com/beidou/home/market/login")
        mWebView.loadUrl("https://www.baidu.com/")
    }

}
